<template>
  <div class="editor-box">
<!--    <remoteScript src="../../public/tinymce/tinymce.min.js"></remoteScript>-->
    <el-row :gutter="10">
      <el-col :span="12">
        <el-input
            class="editor-title"
            type="text"
            placeholder="请输入标题"
            v-model="title"
            maxlength="100"
            show-word-limit
        />
      </el-col>
      <el-col :span="4" style="line-height: 40px">公开：<el-switch v-model="publicValue" active-color="#13ce66" inactive-color="#ff4949"></el-switch></el-col>
      <el-col :span="4">
        <el-select v-model="classifyChooseValueList" multiple placeholder="选择分类" @visible-change="handleGetClassify">
          <el-option
              v-for="item in classifyLists"
              :key="item.id"
              :label="item.classify_name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select v-model="tagChooseValueList" multiple placeholder="选择标签" @visible-change="handleGettag">
          <el-option
              v-for="item in tagLists"
              :key="item.id"
              :label="item.tag_name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-col>
    </el-row>
    <vue-tinymce v-model="content" :setting="init"/>
<!--    <ed api-key="sadw64q8uefro5aezv17t9b3uke8c87rcpmslk559diip36c" :init="init" v-model="content"></ed>-->
    <button class="editor-btn-upload" @click="uploadArticle()">{{ uploadOrModify }}</button>
  </div>
</template>

<script>
// import Editor from "@tinymce/tinymce-vue";
import {getArticle, listClassify, listTags, uploadArticle} from "@/api/apis";
import {mapGetters} from "vuex";
import Prism from "@/assets/js/prism"
import {fileUpload} from "@/api/request";

export default {
  name: "editor",
  components:{
    // 'ed':Editor
    // remoteScript,
  },
  created() {
    if (this.$route.path === '/editor-modify'){
      this.uploadOrModify = '更新'
      this.isModify = true
      this.articleId = this.$route.params.id
      this.handleGetArticle(this.articleId)
    }
    this.checkLoginStatus();
  },
  data(){
    return{
      title: '',
      publicValue: true,
      classifyLists: [],
      classifyChooseValueList: [],
      uploadOrModify: '上传',
      isModify: false,
      content: '',
      tagChooseValueList: [],
      tagLists: [],
      // content: '<pre class="language-javascript"><code>JSON.parse(wndow.localStrage.getItem(\'name\'))</code></pre><h1 style="text-align: center;">长恨歌</h1><p style="text-align: center;">汉皇重色思倾国，御宇多年求不得。<br />杨家有女初长成，养在深闺人未识。<br />天生丽质难自弃，一朝选在君王侧。<br />回眸一笑百媚生，六宫粉黛无颜色。<br />春寒赐浴华清池，温泉水滑洗凝脂。<br />侍儿扶起娇无力，始是新承恩泽时。<br />云鬓花颜金步摇，芙蓉帐暖度春宵。<br />春宵苦短日高起，从此君王不早朝。<br />承欢侍宴无闲暇，春从春游夜专夜。<br />后宫佳丽三千人，三千宠爱在一身。<br />金屋妆成娇侍夜，玉楼宴罢醉和春。<br />姊妹弟兄皆列土，可怜光彩生门户。<br />遂令天下父母心，不重生男重生女。<br />骊宫高处入青云，仙乐风飘处处闻。<br />缓歌慢舞凝丝竹，尽日君王看不足。<br />渔阳鼙鼓动地来，惊破霓裳羽衣曲。</p><p style="text-align: center;">九重城阙烟尘生，千乘万骑西南行。<br />翠华摇摇行复止，西出都门百余里。<br />六军不发无奈何，宛转蛾眉马前死。<br />花钿委地无人收，翠翘金雀玉搔头。<br />君王掩面救不得，回看血泪相和流。<br />黄埃散漫风萧索，云栈萦纡登剑阁。<br />峨嵋山下少人行，旌旗无光日色薄。<br />蜀江水碧蜀山青，圣主朝朝暮暮情。<br />行宫见月伤心色，夜雨闻铃肠断声。<br />天旋日转回龙驭，到此踌躇不能去。<br />马嵬坡下泥土中，不见玉颜空死处。<br />君臣相顾尽沾衣，东望都门信马归。<br />归来池苑皆依旧，太液芙蓉未央柳。<br />芙蓉如面柳如眉，对此如何不泪垂。<br />春风桃李花开夜，秋雨梧桐叶落时。<br />西宫南苑多秋草，落叶满阶红不扫。<br />梨园弟子白发新，椒房阿监青娥老。<br />夕殿萤飞思悄然，孤灯挑尽未成眠。<br />迟迟钟鼓初长夜，耿耿星河欲曙天。<br />鸳鸯瓦冷霜华重，翡翠衾寒谁与共。<br />悠悠生死别经年，魂魄不曾来入梦。</p><p style="text-align: center;">临邛道士鸿都客，能以精诚致魂魄。<br />为感君王辗转思，遂教方士殷勤觅。<br />排空驭气奔如电，升天入地求之遍。<br />上穷碧落下黄泉，两处茫茫皆不见。<br />忽闻海上有仙山，山在虚无缥缈间。<br />楼阁玲珑五云起，其中绰约多仙子。<br />中有一人字太真，雪肤花貌参差是。<br />金阙西厢叩玉扃，转教小玉报双成。<br />闻道汉家天子使，九华帐里梦魂惊。<br />揽衣推枕起徘徊，珠箔银屏迤逦开。<br />云鬓半偏新睡觉，花冠不整下堂来。</p><p style="text-align: center;">风吹仙袂飘飖举，犹似霓裳羽衣舞。<br />玉容寂寞泪阑干，梨花一枝春带雨。<br />含情凝睇谢君王，一别音容两渺茫。<br />昭阳殿里恩爱绝，蓬莱宫中日月长。<br />回头下望人寰处，不见长安见尘雾。<br />惟将旧物表深情，钿合金钗寄将去。<br />钗留一股合一扇，钗擘黄金合分钿。<br />但令心似金钿坚，天上人间会相见。</p><p style="text-align: center;">临别殷勤重寄词，词中有誓两心知。<br />七月七日长生殿，夜半无人私语时。<br />在天愿作比翼鸟，在地愿为连理枝。<br />天长地久有时尽，此恨绵绵无绝期。</p>',
      init: {
        // skin: "snow",  // 高级版皮肤 无法使用
        icons: "custom",
        menubar: true,
        toolbar_drawer: "sliding",
        quickbars_selection_toolbar: "removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor",
        language_url: '/tinymce/lang/zh_CN.js',
        language: 'zh_CN',
        height: window.innerHeight - 200,
        // width: window.innerWidth - 100,
        // skin_url: '../assets/tinymce/skins/ui/oxide',
        branding: false,
        toolbar: " fullscreen | undo redo | fontselect fontsizeselect forecolor backcolor alignleft aligncenter alignright " +
            " alignjustify | formatselect codesample link lineheight | numlist bullist | image media table bdmap |  " +
            " bold italic underline strikethrough | indent outdent | superscript subscript | " +
            " removeformat | searchreplace insertdatetime hr emoticons charmap preview help ",
        plugins: [
          'advlist autolink lists link image imagetools charmap print preview anchor',
          'searchreplace visualblocks code fullscreen preview emoticons bdmap textpattern',
          'insertdatetime media table paste help wordcount codesample hr quickbars'
        ],
        // codesample_content_css: '../assets/css/prism.css',   // 代码示例引用自定义的css文件
        // codesample_content_css: './tinymce/lang/prism.css',   // 代码示例引用自定义的css文件
        codesample_global_prismjs: true,
        imagetools_cors_hosts: ['127.0.0.1'],   // 单击图片显示工具按钮 图片来源跨域白名单
        // images_upload_url: '',  //指定一个接受上传文件的后端处理程序地址 会添加上传tab
        // 文件上传函数
        // images_upload_base_path: '/demo',   // 给相对路径指定它所相对的基本路径。
        file_picker_callback: this.handleUploadFile,
        codesample_languages: [
          {text: 'Python', value: 'python'},
          {text: 'HTML/XML', value: 'markup'},
          {text: 'JavaScript', value: 'javascript'},
          {text: 'CSS', value: 'css'},
          {text: 'PHP', value: 'php'},
          {text: 'Ruby', value: 'ruby'},
          {text: 'Java', value: 'java'},
          {text: 'C', value: 'c'},
          {text: 'C#', value: 'csharp'},
          {text: 'C++', value: 'cpp'}
        ],
        textpattern_patterns: [
          {start: '*', end: '*', format: 'italic'},
          {start: '**', end: '**', format: 'bold'},
          {start: '#', format: 'h1'},
          {start: '##', format: 'h2'},
          {start: '###', format: 'h3'},
          {start: '####', format: 'h4'},
          {start: '#####', format: 'h5'},
          {start: '######', format: 'h6'},
          {start: '1. ', cmd: 'InsertOrderedList'},
          {start: '* ', cmd: 'InsertUnorderedList'},
          {start: '- ', cmd: 'InsertUnorderedList'},
          {start: '//brb', replacement: 'Be Right Back'}
        ],
      }
    }
  },
  computed:{
    ...mapGetters([
      'login_status',
    ]),
  },
  methods:{
    uploadArticle() {
      if (this.title === ''){
        this.$message.error('标题不能为空')
        return
      }
      if (this.content === ''){
        this.$message.error('没有编辑内容')
        return
      }
      this.$confirm(`是否${this.uploadOrModify}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        let params = new URLSearchParams()
        params.append('title', this.title)
        params.append('public', this.publicValue)
        params.append('classifies', this.classifyChooseValueList)
        params.append('tags', this.tagChooseValueList)
        params.append('content', this.content)
        // 只获取文本内容
        const activeEditor = this.$tinymce.activeEditor;
        activeEditor.selection.select(activeEditor.getBody());
        const txtContent = activeEditor.selection.getContent({'format': 'text'});
        params.append('text_content', txtContent)
        // console.log('---------------')
        // console.log(txtContent)
        if(this.isModify){
          params.append('is_modify', true)
          params.append('modify_id', this.articleId)
        }
        uploadArticle(params).then(response => {
          // console.log('成功')
          // console.log(response)
          this.$message({
            type: 'success',
            message: this.uploadOrModify + '成功!'
          });
        }).catch(err => {
          // console.log('失败')
          // console.log(err)
          this.$message({
            type: 'error',
            message: err.data.message
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消' + this.uploadOrModify
        });
      });
    },
    handleClassifyChange(command){
      // command 来自下拉按钮中的:command对应的数据
      console.log(command)
      // alert('you click btn')
    },
    handleGetClassify(status){
      // 出现则为 true，隐藏则为 false
      if(status){
        listClassify().then(response => {
          this.classifyLists = response.data
        }).catch(err => {
          this.$message.error('获取分类列表时出错')
        })
      }
    },
    handleGettag(){
      listTags().then(response => {
        this.tagLists = response.results.data
      }).catch(err => {
        this.$message.error(err.data.message)
      })
    },
    checkLoginStatus(){
      if (this.login_status !== '1'){
        this.$message.warning('没有登录 不能使用编辑器 已跳转至首页')
        this.$router.push({path: '/'})
      }
    },
    handleUploadFile(callback, value, meta) {
      let that = this
      //   //文件分类
      let file_accept = '.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4';
      //   //后端接收上传文件的地址
      //   var upurl = '/demo/upfile.php';
      //   //为不同插件指定文件类型及后端地址
      let url = 'article/upload-file/'
      switch (meta.filetype) {
        case 'image':
          file_accept = '.jpg, .jpeg, .png, .gif';    // 浏览器中上传文件选择时的默认筛选格式 对应下面的accept
          url = 'article/upload-image/'
          break;
        case 'media':
          file_accept = '.mp3, .mp4';
          url = 'article/upload-media/'
          break;
        case 'file':
        default:
      }
      //模拟出一个input用于添加本地文件
      const input = document.createElement('input');
      input.setAttribute('type', 'file');
      input.setAttribute('accept', file_accept);
      input.click();
      input.onchange = function () {
        const file = this.files[0];
        let params = new FormData()
        params.append('file', file, file.name)
        fileUpload(url, params).then(response => {
          // console.log(response)
          that.$message.success('上传成功')
          callback(response.data.url, response.data.others)
        }).catch(err => {
          // console.log(err)
          that.$message.error(err.data.message)
        })
      }
    },
    handleGetArticle(id){
      getArticle(id).then(response =>{
        this.handleGetClassify(true)
        this.content = response.data.content
        this.title = response.data.title
        this.publicValue = response.data.public
        response.data.classifies.forEach(item => {
          this.classifyChooseValueList.push(item.id)
        })
        // this.classifyChooseValueList = response.data.classifies
        response.data.tags.forEach(item => {
          this.tagChooseValueList.push(item.id)
        })
        // this.tagChooseValueList = response.data.tags
      }).catch(err => {
        this.$message.error(err.data.message)
      })
    }
  },
  watch:{
    content:{
      handler() {
        setTimeout(() => {
          Prism.highlightAll() // 这里加定时器让它后执行，不然没效果
        }, 0)
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
/*@import "public/tinymce/lang/prism.css";*/
  .editor-box{
    width: 1000px;
    margin: 20px auto 0;
  }
  .editor-title {
    width: 90%;
    height: 40px;
    border-radius: 5px;
    margin: 0 auto 10px;
  }
  .editor-btn-upload{
    color: white;
    background-color: #409eff;
    margin: 10px;
    border: none;
    border-radius: 5px;
    padding: 10px 20px;
  }
</style>
